import { createContext } from "solid-js";
import { TypeSwitch } from "../type";
import { createStore } from "solid-js/store";


export const getSwitchContext: () => TypeSwitch.State = (() => {
  const [switchState, setSwitchState] = createStore<TypeSwitch.Focus>({
    focusId: "",
  });
  const _state: TypeSwitch.StateValue = {
    focus: switchState,
    widgetList: [],
    boxList: [],
  }
  //数据中心配置
  const _option: TypeSwitch.StateOptions = {
    /**widget创建或者销毁需要触发该事件 */
    widgetChange(item) {
      const _idx = _state.widgetList.findIndex(v => v.uid === item)
      if (typeof item === "string") {
        _state.widgetList.splice(_idx, 1)
        return
      }
      if (!switchState.focusId) {
        setSwitchState("focusId", item.uid)
      }
      if (_idx > -1) {
        _state.widgetList[_idx] = item
      } else {
        _state.widgetList.push(item)
      }
    },
    /**box创建或者销毁需要触发该事件 */
    boxChange(item) {
      const _idx = _state.boxList.findIndex(v => v.uid === item)
      if (typeof item === "string") {
        _state.boxList.splice(_idx, 1)
        return
      }
      if (_idx > -1) {
        _state.boxList[_idx] = item
      } else {
        _state.boxList.push(item)
      }
    },
    changeFocus(ev) {
      setSwitchState("focusId", ev)
    },
  }
  return [_state, _option]
});

export const SwitchContext = createContext<TypeSwitch.State>(getSwitchContext());